package com.fosdata.dpm.util;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.fosdata.dpm.constant.AppSecrtConstant;
import com.fosdata.dpm.domain.SysUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class WxJsSdkSignUtil {

    private static final Logger logger = LoggerFactory.getLogger(WxJsSdkSignUtil.class);
    /**
     * 生成随机字符串（nonceStr）
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
    }

    /**
     * 生成时间戳（timestamp，秒级）
     */
    public static long generateTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成签名（signature）
     * @param jsapiTicket 微信获取的 jsapi_ticket（需先通过 access_token 获取，有效期 7200 秒）
     * @param url 前端页面的完整 URL（需与前端实际访问的 URL 一致，包括参数）
     * @param nonceStr 随机字符串
     * @param timestamp 时间戳
     */
    public static String generateSignature(String jsapiTicket, String url, String nonceStr, long timestamp) {
        // 拼接签名字符串：jsapi_ticket=xxx&noncestr=xxx&timestamp=xxx&url=xxx
        String signStr = String.format(
                "jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s",
                jsapiTicket, nonceStr, timestamp, url
        );
        // SHA1 加密并返回
        return DigestUtils.sha1Hex(signStr);
    }

    public static JSONObject  getSignature(String appurl){
        //链式构建请求,  获取token
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("grant_type","client_credential");
        paramMap.put("appid",AppSecrtConstant.APPID);
        paramMap.put("secret",AppSecrtConstant.APPSecret);
        String result2 = HttpRequest.get(AppSecrtConstant.GET_WECHAT_TOKEN_URL)
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        logger.info("获取的微信access_token = "+result2);
        JSONObject tokenJson =  JSONObject.parseObject(result2);
        String access_token  = tokenJson.getString("access_token");
        logger.info("解析后的access_token  is : "+ access_token);
        /**获取jsapiTicket**/
        Map<String,Object> jsapiMap = new HashMap<>();
        jsapiMap.put("access_token",access_token);
        jsapiMap.put("type","jsapi");
        String jsapi = HttpRequest.get(AppSecrtConstant.GET_WECHAT_JSAPI_URL)
                .form(jsapiMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        logger.info("获取的微信jsapi  is : "+ jsapi);
        JSONObject jsapiJson =  JSONObject.parseObject(jsapi);
        String jsapiTick  = jsapiJson.getString("ticket");
        logger.info("解析后的jsapiTick  is : "+ jsapiTick);
        String nonceStr = generateNonceStr();
        long timestamp = generateTimestamp();
        // 5. 生成 signature
        String signature = generateSignature(jsapiTick, appurl, nonceStr, timestamp);
        logger.info("根据jsApi和url 生成的signature  is : "+ signature);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("timestamp",timestamp);
        jsonObject.put("nonceStr",nonceStr);
        jsonObject.put("signature",signature);
        return jsonObject;
    }



    // 测试示例
    public static void main(String[] args) {
       JSONObject jsonObject =  getSignature("https://your-domain.com/path?param=123");

       logger.info("测试返回数据："+ jsonObject.toJSONString());
    }
}
